package com.easy.dfcshop.service.impl;

import com.easy.common.bean.Result;
import com.easy.common.constant.EnumConfig;
import com.easy.common.utils.SpringContextHolder;

import com.easy.dfcapi.utils.Util;
import com.easy.dfcshop.entity.Img;
import com.easy.dfcshop.mapper.ImgMapper;
import com.easy.dfcshop.response.ImageRes;
import com.easy.dfcshop.service.ImageService;
import com.easy.modules.sys.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by VULCANTSeries on 2017/5/10.
 */
@Service
public class ImageServiceImpl implements ImageService {

    @Autowired
    private ImgMapper imgMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result UploadImg(ImageRes image, HttpServletRequest request) throws IOException, Exception {
        Result rt = new Result();
        try{
           // Img data = response.getData(Img.class);


            List<ImageRes> list = new ArrayList();
            //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                    request.getSession().getServletContext());
            //检查form中是否有enctype="multipart/form-data"

            if (multipartResolver.isMultipart(request)) {
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                //获取multiRequest 中所有的文件名
                Iterator iter = multiRequest.getFileNames();

                Date now = new Date();
                while (iter.hasNext()) {
                    //一次遍历所有文件
                    MultipartFile file = multiRequest.getFile(iter.next().toString());
                    if (file != null) {

                        String key = new Date().getTime() + file.getOriginalFilename();
                        Util.OSSUpload("productpictures", key, file.getInputStream());
                        //String path = "http://factoryimgs.oss-cn-shanghai.aliyuncs.com/" + key;
                        String ossPath = "http://productpictures.oss-cn-shanghai.aliyuncs.com/" + key;


                        // 文件保存路径
                        String filePath = request.getSession().getServletContext().getRealPath("/") + "userfiles/admin/upload/";
                        String webPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+SpringContextHolder.getContextPath()+ "/userfiles/admin/upload/";
                        File tfile = new File(filePath);
                        if(!tfile.exists()){
                            tfile.mkdirs();
                        }
                        // 转存文件
                        file.transferTo(new File(filePath+ key));

                        Img apiImg = new Img();

                        apiImg.setImgOssUrl(ossPath);
                        apiImg.setImgUrl(webPath+ key);
                        apiImg.setImgType(1);
                        apiImg.preInsert(now);
                        imgMapper.insert(apiImg);


                        ImageRes timg = new ImageRes();
                        timg.setImgId(apiImg.getImgId());
                        timg.setImgUrl(webPath+ key);
                        timg.setImgOssUrl(ossPath);
                        timg.setImgName(file.getName());
                        list.add(timg);
                    }
                }
            }
            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(list);
        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }
        return rt;
    }
}
